package lib
import (
	"github.com/funlake/gopkg/utils/log"
	//"fmt"
	"os"
	"sync"
	_cache "github.com/funlake/gopkg/cache"
)

var (
	cache *Cache
	cacheSync sync.Once
	timerCache = _cache.NewTimerCacheRedis()
	redisStore = _cache.NewKvStoreRedis()
	//localCache = map[string] string{}
)
func initCache() {
	cacheSync.Do(func() {
		redisStore.Connect(os.Getenv("PQ_REDIS_HOST")+":"+os.Getenv("PQ_REDIS_PORT"),os.Getenv("PQ_REDIS_PASSWORD"))
		timerCache.SetStore(redisStore)
		cache = &Cache{timercache:timerCache}
	})
}
func NewCache() *Cache {
	initCache()
	return cache
}
//var refreshTimer = map[string] *time.Ticker{}
type Cache struct {
	timercache *_cache.TimerCacheRedis
}
func (this *Cache) Flush(){
	this.timercache.Flush()
}

func (this *Cache) GetUpstream(vk string) (string,error){
	//return this.HashGet("gateway:proxy",vk,60)
	return this.timercache.Get("gateway:proxy",vk,300)
}
func (this *Cache) GetMultiUpstream(vk string) (string,error){
	log.Info("multi_rote:====================" +vk+"===============")
	//Found wired bug here,receive same value from different key,so fucking strange
	//Keep log it and see what happen
	routes,err := this.timercache.Get("gateway:multiproxy",vk,300)
	log.Info(routes)
	if vk == "v1/home" {
		return `[{"api":"pq.zhimagk.com/v1/user/stat","method":"GET","respcode":"stat_info","params":"mode=skiproot","cachekey":"si","block":true,"cache":true,"default":[{}]},{"api":"pq.zhimagk.com/v1/user/test_category/point_category","method":"GET","respcode":"point_category","params":"","cachekey":"pc","block":true,"cache":true,"default":[{}]}]`,nil
	}
	if vk == "v1/cate" {
		return `[{"api":"pq.zhimagk.com/v1/test_categories/code/CS_ROOT","method":"GET","respcode":"cs_cate","params":"mode=skiproot","cachekey":"si","block":true,"cache":false,"default":[{}]},{"api":"pq.zhimagk.com/v1/test_categories/code/SL_ROOT","method":"GET","respcode":"sl_cate","params":"","cachekey":"pc","block":true,"cache":false,"default":[{}]}]`,nil
	}

	return routes,err
}
func (this *Cache) GetAcl(vk string) (string,error){
	return this.timercache.Get("gateway:acl",vk,120)
}
func (this *Cache) GetAclCheck(vk string) (string,error)  {
	return this.timercache.Get("gateway:aclignore",vk,60)
}
func (this *Cache) GetRateLimit(vk string) (string,error){
	return this.timercache.Get("gateway:ratelimit",vk,60)
}
func (this *Cache) SetRateLimitLeft(vk string ,vv string)  (error){
	_,err:= this.timercache.GetStore().HashSet("gateway:ratelimitleft",vk,vv)
	return err
}
func (this *Cache) GetRateLimitLeft(vk string )  (string,error){
	return this.timercache.Get("gateway:ratelimitleft",vk,60)
}
func (this *Cache) GetAppInfo(access_token string) (string,error) {
	return this.timercache.Get("","OPEN_token:"+access_token,30)
}
func (this *Cache) GetCircuitBreakerSetting(service string) (string,error){
	return this.timercache.Get("gateway:circuitbreaker",service ,60)
}